<template>
  <div id="station-map"></div>
</template>

<script>
const BMap = window.BMap;
let map = null;
import { getStastionsMap } from "@/api/user";
export default {
  name: 'StationMap',
  data() {
    return {};
  },
  computed: {
    comId() {
      return this.$store.getters.comId;
    }
  },
  mounted() {
    map = new BMap.Map("station-map");
    const p = [106.504108, 29.598395];
    const point = new BMap.Point(p[0], p[1]);
    map.centerAndZoom(point, 14);
    map.setCurrentCity("重庆");
    map.enableScrollWheelZoom(true);
    getStastionsMap(this.comId).then(data => {
      this.loadStations(data);
    });
  },
  methods: {
    loadStations(ls) {
      ls.forEach(l => {
        const p = l.location.split(",");
        const mp = new BMap.Point(p[0], p[1]);
        const maker = new BMap.Marker(mp, { title: l.name });
        maker.addEventListener("click", e => {
          this.wndHander(l.name, mp);
        });
        map.addOverlay(maker);
      });
    },
    wndHander(name, point) {
      var myGeo = new BMap.Geocoder();
      // 根据坐标得到地址描述
      myGeo.getLocation(point, result => {
        if (result) {
          let address;
          const p = result.surroundingPois[0];
          if (!p) {
            address = result.address;
          } else {
            address = p.address;
          }
          var opts = {
            width: 200, // 信息窗口宽度
            height: 100, // 信息窗口高度
            title: name // 信息窗口标题
          };
          var infoWindow = new BMap.InfoWindow("地址：" + address, opts);
          map.openInfoWindow(infoWindow, point);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
#station-map {
  width: 100%;
  height: 100%;
}
</style>
